<?php

/**
 * usuario actions.
 *
 * @package    Terapia Vital
 * @subpackage usuario
 * @author     Foxsis
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class usuarioActions extends sfActionsFoxsis
{
	public function executeIndex(sfWebRequest $request)
	{
		return $this->forward('usuario', 'list');
	}

	public function executeGrid()
	{
		//Recupero todas as informações necessárias para trabalhar com o grid
		$this->getRequestDataTable();
		$this->data					= sfGuardUserTable::consultar($this->filter, $this->order);
		$this->total_data			= count($this->data);
		$this->data					= $this->paginadorDataTable($this->data, $this->page_num, parent::LIMIT_PAGE_DATA_TABLE);

		sfLoader::loadHelpers(array('Url'));

		foreach($this->data as $key => $r)
		{
			$actions = array(
				'edit'	 => "<a href='".url_for($this->getModuleName().'/edit?id='.$r['id'])."' class='icoEditar'></a>",
				'delete' => "<a href='".url_for($this->getModuleName().'/delete?id='.$r['id'])."'  class='icoExcluir delete'></a>",
			);
			$this->data[$key]['act'] = implode(' ', $actions);
		}

		$this->setJSONDataTable($this->data, $this->colunas, $this->total_data);
		return sfView::NONE;
	}


	public function executeList()
	{
		$this->form = new sfGuardUserForm();
		$this->colunas	= array(
		$this->form['id']->renderLabel() => "id",
		$this->form['username']->renderLabel() => "username",
		$this->form['algorithm']->renderLabel() => "algorithm",
		$this->form['salt']->renderLabel() => "salt",
		$this->form['password']->renderLabel() => "password",
		$this->form['is_active']->renderLabel() => "is_active",
		$this->form['is_super_admin']->renderLabel() => "is_super_admin",
		$this->form['last_login']->renderLabel() => "last_login",
		$this->form['created_at']->renderLabel() => "created_at",
		$this->form['updated_at']->renderLabel() => "updated_at",
						"Ações"	=> "act"
						);

						$this->filter = $this->_getFilter();

						$this->setTemplate('index');
	}

	public function executeFilter()
	{
		$filter = new Filtro(
		$this->getRequestParameter(sfActionsFoxsis::FILTER_SESSION_USER_ATTRIBUTE)
		);

		$filter->setCulture($this->getUser()->getCulture());
		$this->getUser()->setAttribute('pg_num',1,$this->getModuleName());

		$this->getUser()->setAttribute(
		sfActionsFoxsis::FILTER_SESSION_USER_ATTRIBUTE,
		serialize($filter),
		$this->getModuleName()
		);

		return $this->forward($this->getModuleName(), '/list');
	}

	public function executeShow(sfWebRequest $request)
	{
		$this->sf_guard_user = Doctrine::getTable('sfGuardUser')->find(array($request->getParameter('id')));
		$this->forward404Unless($this->sf_guard_user);
	}

	public function executeNew(sfWebRequest $request)
	{
		$this->form = new sfGuardUserForm();
	}

	public function executeCreate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST));

		$this->form = new sfGuardUserForm();

		$this->processForm($request, $this->form);

		$this->forward($this->getModuleName(), 'new');
	}

	public function validateCreate()
	{
		return true;
	}

	public function handleErrorCreate()
	{
		return $this->forward($this->getModuleName(), 'new');
	}

	public function executeEdit(sfWebRequest $request)
	{
		$this->forward404Unless($sf_guard_user = Doctrine::getTable('sfGuardUser')->find(array($request->getParameter('id'))), sprintf('Object sf_guard_user does not exist (%s).', $request->getParameter('id')));
		$this->form = new sfGuardUserForm($sf_guard_user);
	}

	public function executeUpdate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
		$this->forward404Unless($sf_guard_user = Doctrine::getTable('sfGuardUser')->find(array($request->getParameter('id'))), sprintf('Object sf_guard_user does not exist (%s).', $request->getParameter('id')));
		$this->form = new sfGuardUserForm($sf_guard_user);

		$this->processForm($request, $this->form);

		$this->forward($this->getModuleName(), 'edit');
	}

	public function validateUpdate()
	{
		return true;
	}

	public function handleErrorUpdate()
	{
		return $this->forward($this->getModuleName(), 'edit');
	}

	public function executeDelete(sfWebRequest $request)
	{
		try
		{
			$request->checkCSRFProtection();

			$this->forward404Unless($sf_guard_user = Doctrine::getTable('sfGuardUser')->find(array($request->getParameter('id'))), sprintf('Object sf_guard_user does not exist (%s).', $request->getParameter('id')));
			$sf_guard_user->delete();

			$this->redirect('usuario/index');
		}
		catch(Excepiton $e)
		{
			$this->getUser()->setFlash('erro', $e->getMessage());
			$this->redirect('usuario/index');
		}

	}

	protected function processForm(sfWebRequest $request, sfForm $form)
	{
		try
		{
			$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
			if ($form->isValid())
			{
				$sf_guard_user = $form->save();
				$this->getUser()->setFlash('mensagem', 'Dados salvos com sucesso.');
				$this->redirect('usuario/edit?id='.$sf_guard_user->getId());
			}
			else
			{
				throw new Exception($form->getErrorSchema());
			}
		}
		catch(Exception $e)
		{
			$this->getUser()->setFlash('erro', $e->getMessage());
		}
	}
	
	public function executeMeusDados()
	{
		try
		{
			$user_id = $this->getUser()->getGuardUser()->getId();
			$this->forward404Unless(
				$this->usuario = Doctrine::getTable('DadosUsuario')->find($user_id), 
				sprintf('Object sf_guard_user_profile does not exist (%s).', $user_id)
			);
			
			$this->form = new DadosUsuarioForm($this->usuario);
		}
		catch(Exception $e)
		{
			$this->getUser()->setFlash('erro', $e->getMessage());
			$this->redirect('homepage');
		}
	}
	
	public function executeAtualizarDados(sfWebRequest $request)
	{
		try
		{	
			Doctrine_Manager::getInstance()->getCurrentConnection()->beginTransaction();
			
			$formData = new FormData($this->getRequestParameter('dados_usuario'));
			$formData->setCulture($this->getUser()->getCulture());
			
			$usuario = Doctrine::getTable('DadosUsuario')->find($formData->get('id_dados_usuario'));
			$usuario->set('no_usuario',	$formData->get('no_usuario'));
			$usuario->set('sobrenome', 	$formData->get('sobrenome'));
			$usuario->set('email', 		$formData->get('email'));
			
			if($formData->get('password') != '')
			{
				$sfuser = Doctrine::getTable('sfGuardUser')->find($formData->get('id_dados_usuario'));
				
				//$novaSenha = sha1($formData->get('password'));
				$sfuser->set('password', $formData->get('password'));
				$sfuser->save();
			}
			
			$usuario->save();
			
			Doctrine_Manager::getInstance()->getCurrentConnection()->commit();
			$this->getUser()->setFlash('mensagem', 'Dados salvos com sucesso.', true);
			
			return $this->redirect('usuario/meusDados');
		}
		catch(Exception $e)
		{
			Doctrine_Manager::getInstance()->getCurrentConnection()->rollback();
			$this->getUser()->setFlash('erro', $e->getMessage(), true);
			return $this->forward($this->getModuleName(), 'meusDados');	
		}
	}
	
	public function validateAtualizarDados()
	{
		if($this->getRequestParameter('dados_usuario[password]'))
		{
			if($this->getRequestParameter('dados_usuario[password2]') == "")
			{
				$this->getRequest()->setError("dados_usuario{password2}", "O campo CONFIRMAÇÃO DE SENHA é obrigatório.");
			}
			else 
			if ($this->getRequestParameter('dados_usuario[password2]') != $this->getRequestParameter('dados_usuario[password]'))
			{
				$this->getRequest()->setError("dados_usuario{password2}", "O campo CONFIRMAÇÃO DE SENHA tem que ser igual ao campo SENHA.");
			}	
		}
		
		if ($this->getRequest()->getErrors())
			return false;
		else
			return true;
	}
	
	public function handleErrorAtualizarDados()
	{
		return $this->forward($this->getModuleName(), 'meusDados');
	}
}
